<?php

namespace Yxy\YJson;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Response;

/**
 * 返回Json数据
 */
class Json
{
    /**
     * 处理响应
     * @param int $status 状态码
     * @param mixed $message 提示信息
     * @param array|null $data 数据
     * @return JsonResponse
     */
    public static function create(int $status, mixed $message, ?array $data = null): JsonResponse
    {
        $messageText = '失败';
        if ($status == 200) {
            $messageText = '成功';
        }

        if (is_array($message)) {
            $data = $message;
            $message = $messageText;
        }

        if (is_object($message)) {
            $data = json_decode(json_encode($message), true);
            $message = $messageText;
        }

        if (empty($message)) {
            $data = [];
            $message = $messageText;
        }
        $res = empty($data) ? compact('status', 'message') : compact('status', 'message', 'data');

        return Response::json($res);
    }

    /**
     * 返回成功信息
     * @param mixed $message
     * @param array|null $data
     * @return JsonResponse
     */
    public static function success(mixed $message = '成功', ?array $data = null): JsonResponse
    {
        return self::create(200, $message, $data);
    }

    /**
     * 返回失败信息
     * @param mixed $message
     * @param array|null $data
     * @return JsonResponse
     */
    public static function fail(mixed $message = '失败', ?array $data = null): JsonResponse
    {
        return self::create(400, $message, $data);
    }


    /**
     * 返回layui表格数据
     * @param array $data
     * @return JsonResponse
     */
    public static function table(array $data = []): JsonResponse
    {
        return Response::json(['code' => 0, 'data' => $data['list'] ?? $data, 'count' => $data['count'] ?? 0, 'msg' => '成功']);
    }
}
